import storage from '@/utils/storage';
import { decrypt } from '@/utils/jsencrypt';
import NProgress from 'nprogress'; // progress bar
import { Message } from '@arco-design/web-vue';
import 'nprogress/nprogress.css';
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/store';
import { appRoutes } from './routes';
import { initRouterNode } from '@/hooks/roleRouter';
// NProgress Configuration
NProgress.configure({ showSpinner: true });
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: 'login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    {
      path: '/app-invent',
      name: 'app-invent',
      component: () =>
        import('@/views/operation/decoration/app/app-invent.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    {
      path: '/pc-invent',
      name: 'pc-invent',
      component: () => import('@/views/operation/decoration/pc/pc-invent.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    {
      path: '/workplace',
      name: 'Workplace',
      component: () => import('@/layout/default-layout.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    ...appRoutes,
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/not-found/index.vue'),
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});
function isHttp(url) {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1;
}
function redirectToLoginUrl() {
  useUserStore()
    .getTongYiSystemUrl()
    .then((url: any) => {
      if (!isHttp(url)) {
        Message.error('未获取到登录地址, 请联系管理员');
        return;
      }
      window.location.replace(url);
    })
    .catch((err) => {
      console.log('获取登录地址报错', err);
    });
}
router.beforeEach((to: any, from: any, next: any) => {
  NProgress.start();
  const { _t } = to.query;
  if (_t) {
    storage.clearToken();
    storage.setAccessToken(decrypt(_t));
    const query = { ...to.query };
    delete query._t;
    initRouterNode(true);
    next({
      path: to.path,
      query,
      replace: true,
    });
  }
  const title = to.name;
  const token: any = storage.getAccessToken();

  if (!token) {
    // 判断未登录
    const isDevelopment = process.env.NODE_ENV === 'development';
    // const isDevelopment = false;
    if (isDevelopment) {
      if (title != 'login') {
        next({ name: 'login' });
      }
    } else {
      redirectToLoginUrl();
      NProgress.done();
      return;
    }
  }
  if (token && title == 'login') {
    // 判断已登录且前往的页面是登录页
    next({ path: 'Workplace' });
  } else {
    next();
  }
  NProgress.done();
});

export default router;
